//
//  GiftViewController.m
//  FlyGift
//
//  Created by lanou3g on 15/7/14.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "GiftViewController.h"
@interface GiftViewController ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate>
@property(nonatomic, strong)ChooseGiftView *chooseView;
@property(nonatomic, strong)UITableView *leftTable;
@property(nonatomic, strong)UICollectionView *rightCollection;
@property(nonatomic, strong)NSMutableArray *categoryNameArray;
@property(nonatomic, strong)NSMutableArray *categoriesArray;
@property(nonatomic, strong)NSMutableArray *subcategoriesArray;
@property(nonatomic, strong) GiftModel *model;


//@property(copy,nonatomic,readonly) id block;

/**  滚动到指定的行数*/
@property(assign,nonatomic) NSInteger needToScorllerIndex;

/**  颜色属性配置*/
/**  左边背景颜色*/
@property(strong,nonatomic) UIColor * leftBgColor;
/**  左边点中文字颜色*/
@property(strong,nonatomic) UIColor * leftSelectColor;
/**  左边点中背景颜色*/
@property(strong,nonatomic) UIColor * leftSelectBgColor;
/**  左边未点中文字颜色*/
@property(strong,nonatomic) UIColor * leftUnSelectColor;
/***  左边未点中背景颜色*/
@property(strong,nonatomic) UIColor * leftUnSelectBgColor;
@property(assign,nonatomic,readonly) NSInteger selectIndex;

@end







@implementation GiftViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 调用数据解析
    [self giftSortDataRequest];
    
    // 选择状态下的字体颜色是粉色 背景是白色
    self.leftSelectColor=kMainColor;
    self.leftSelectBgColor=[UIColor whiteColor];
    
    // 未选择状态下字体是黑色的
    self.leftUnSelectColor=[UIColor blackColor];
    self.leftUnSelectBgColor= KColor(242, 243, 238, 1);
    
    // 默认状态下显示的下标是0
    _selectIndex = 0;
    
    
    /**选礼神器*/
    self.chooseView = [[ChooseGiftView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kP6Height(35))];
    [self.view addSubview:_chooseView];
    
    /***  左边的视图 (显示分类)*/
    self.leftTable = [[UITableView alloc]initWithFrame:CGRectMake(0, self.chooseView.frame.size.height, kP6width(100), kScreenHeight - 64 - kP6Height(70))];
    self.leftTable.delegate = self;
    self.leftTable.dataSource = self;
    self.leftTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.leftTable.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_leftTable];
    
//    if ([self.leftTable respondsToSelector:@selector(setLayoutMargins:)]) {
//        self.leftTable.layoutMargins=UIEdgeInsetsZero;
//    }
//    if ([self.leftTable respondsToSelector:@selector(setSeparatorInset:)]) {
//        self.leftTable.separatorInset=UIEdgeInsetsZero;
//    }
    
    
    /***  右边的视图 (显示详情排列)*/
    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc]init];
    self.rightCollection = [[UICollectionView alloc]initWithFrame:CGRectMake(kP6width(100) + flowlayout.sectionInset.left, self.chooseView.frame.size.height, kScreenWidth - kP6width(100) - flowlayout.sectionInset.left * 2, kScreenHeight - 64 - kP6Height(70)) collectionViewLayout:flowlayout];
    self.rightCollection.backgroundColor = [UIColor whiteColor];
    self.rightCollection.delegate = self;
    self.rightCollection.dataSource = self;
    [self.view addSubview:_rightCollection];
    
    /***  右边collectionView的自定义header (注册)*/
    [self.rightCollection registerClass:[DisplayHeaderCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"DisplayHeader"];
}

#pragma mark - 重写属性setter方法
-(void)setNeedToScorllerIndex:(NSInteger)needToScorllerIndex{
    if (needToScorllerIndex > 0) {
        /**  滑动到 指定行数*/
        [self.leftTable selectRowAtIndexPath:[NSIndexPath indexPathForRow:needToScorllerIndex inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
        GiftLeftTableViewCell * cell=(GiftLeftTableViewCell*)[self.leftTable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:needToScorllerIndex inSection:0]];
        cell.sortNameLabel.textColor = self.leftSelectColor;
        cell.backgroundColor = self.leftSelectBgColor;
        cell.view.hidden = NO;
        _selectIndex=needToScorllerIndex;
        [self.rightCollection reloadData];
    }
    _needToScorllerIndex=needToScorllerIndex;
}

-(void)setLeftBgColor:(UIColor *)leftBgColor{
    _leftBgColor=leftBgColor;
    self.leftTable.backgroundColor=leftBgColor;
    
}
-(void)setLeftSelectBgColor:(UIColor *)leftSelectBgColor{
    
    _leftSelectBgColor=leftSelectBgColor;
    self.rightCollection.backgroundColor=leftSelectBgColor;
    
    self.view.backgroundColor=leftSelectBgColor;
}

-(void)reloadData{
    
    [self.leftTable reloadData];
    [self.rightCollection reloadData];
    
}



#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.categoryNameArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *tableViewcellIndentifier = @"GiftLeftCell";
    [tableView registerClass:[GiftLeftTableViewCell class] forCellReuseIdentifier:tableViewcellIndentifier];
    GiftLeftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableViewcellIndentifier forIndexPath:indexPath];
    GiftModel *model = self.categoryNameArray[indexPath.row];
    cell.backgroundColor = KColor(111, 111, 111, 1);
    cell.sortNameLabel.text = model.name;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    

    
    
    if (indexPath.row==self.selectIndex) {
        cell.sortNameLabel.textColor=self.leftSelectColor;
        cell.backgroundColor=self.leftSelectBgColor;
        cell.view.hidden = NO;
    }
    else{
        cell.sortNameLabel.textColor=self.leftUnSelectColor;
        cell.backgroundColor=self.leftUnSelectBgColor;
        cell.view.hidden = YES;
    }
    
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        cell.layoutMargins=UIEdgeInsetsZero;
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        cell.separatorInset=UIEdgeInsetsZero;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}


#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    GiftLeftTableViewCell *cell = (GiftLeftTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    cell.sortNameLabel.textColor=self.leftSelectColor;
    cell.backgroundColor=self.leftSelectBgColor;
    cell.view.hidden = NO;
    _selectIndex=indexPath.row;
    
    
    NSLog(@"点击了左边第%ld行分类",indexPath.row);
    NSIndexPath *collectionIndexpath = [NSIndexPath indexPathForItem:0 inSection:indexPath.row];
    [self.rightCollection scrollToItemAtIndexPath:collectionIndexpath atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    GiftLeftTableViewCell * cell=(GiftLeftTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
    cell.sortNameLabel.textColor=self.leftUnSelectColor;
    cell.backgroundColor=self.leftUnSelectBgColor;
    cell.view.hidden = YES;
}



#pragma mark - UICollectionViewDelegateFlowLayout
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 15, 10);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(kP6width(70), kP6Height(100));
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(kScreenWidth, kP6Height(50));
}


#pragma mark - UICollectionViewDataSourse
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSArray *array = self.categoriesArray[section];
    return array.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.categoriesArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *collectionCellIndentifier = @"GiftRightCell";
    [collectionView registerClass:[ImageViewLabelCollectionViewCell class] forCellWithReuseIdentifier:collectionCellIndentifier];
    ImageViewLabelCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionCellIndentifier forIndexPath:indexPath];
    SubcategoriesModel *model = self.categoriesArray[indexPath.section][indexPath.row];
    [cell.giftImageView setImageWithURL:[NSURL URLWithString:model.icon_url]];
    cell.giftNameLabel.text = model.name;
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader])
    {
        
        DisplayHeaderCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"DisplayHeader" forIndexPath:indexPath];
        GiftModel *model = self.categoryNameArray[indexPath.section];
        view.displayNameLabel.text = [NSString stringWithFormat:@"────── %@ ──────",model.name];
        return view;
    }
    else
    {
        return nil;
    }
}


#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    SubcategoriesModel *model = self.categoriesArray[indexPath.section][indexPath.row];
    if (self.clickSubcategoriesItemBlock == nil)
    {
        return;
    }
    self.clickSubcategoriesItemBlock(model.subcategorieId,model.name);
    NSLog(@"点击了右边第%ld个分区的第%ld个礼物",indexPath.section,indexPath.row);
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if ([scrollView isEqual:self.rightCollection])
    {
        
        NSArray *array = self.rightCollection.indexPathsForVisibleItems;
        NSIndexPath *indexPath = self.rightCollection.indexPathsForVisibleItems[array.count / 2];
        NSLog(@"%ld",indexPath.section);
        self.needToScorllerIndex = indexPath.section;
    }
}




#pragma mark - 数据部分
- (void)giftSortDataRequest
{
    self.categoriesArray = [NSMutableArray array];
    [LORequestManger GET:GiftSortURL success:^(id response) {
        
        NSDictionary *categoryDic = (NSDictionary *)response;
        NSDictionary *dataDic = categoryDic[@"data"];
        NSArray *catrgoryArray = dataDic[@"categories"];
        self.categoryNameArray = [NSMutableArray array];
        for (NSDictionary *dic in catrgoryArray)
        {
            GiftModel *model = [[GiftModel alloc]init];
            model.name = dic[@"name"];
            [self.categoryNameArray addObject:model];
            
            self.subcategoriesArray = [NSMutableArray array];
            NSArray *subArray = dic[@"subcategories"];
            for (NSDictionary *subdic in subArray)
            {
                SubcategoriesModel *model = [[SubcategoriesModel alloc]init];
                model.icon_url = subdic[@"icon_url"];
                model.name = subdic[@"name"];
                model.subcategorieId = [subdic[@"id"] stringValue];
                [self.subcategoriesArray addObject:model];
                
            }
            [self.categoriesArray addObject:self.subcategoriesArray];
        }
        
        [self.leftTable reloadData];
        [self.rightCollection reloadData];
    } failure:nil];
}


#pragma mark - 下拉刷新--------未实现
- (void)categoriesPullDownRefresh
{
    // 一旦进入刷新状态即调用self的解析数据方法
//    __block typeof(self) blockSelf = self;
    __weak typeof(self) weakSelf = self;
//    [self.rightCollection addGifHeaderWithRefreshingTarget:self refreshingAction:@selector(giftSortDataRequest)];
    [self.rightCollection addGifHeaderWithRefreshingBlock:^{
        [weakSelf giftSortDataRequest];
        
     }];
    
    // 隐藏时间
    self.rightCollection.header.updatedTimeHidden = YES;
    
    // 设置文字
    [self.rightCollection.header setTitle:@"下拉可以刷新……" forState:MJRefreshHeaderStateIdle];
    [self.rightCollection.header setTitle:@"可以松开啦~" forState:MJRefreshHeaderStatePulling];
    [self.rightCollection.header setTitle:@"奋力加载中~" forState:MJRefreshHeaderStateRefreshing];
    // 设置颜色
    self.rightCollection.header.textColor = kMainColor;
   
    NSMutableArray *idleImages = [NSMutableArray array];
    for (NSUInteger i = 0; i < 2; i++)
    {
        UIImage *image = [UIImage imageNamed: [NSString stringWithFormat:@"icon_loading_action%ld@2x",i + 1]];
        [idleImages addObject:image];
    }
     // 设置普通状态的动画图片
    [self.rightCollection.gifHeader setImages:idleImages forState:MJRefreshHeaderStateIdle];
    // 设置即将刷新状态下的动画
    [self.rightCollection.gifHeader setImages:idleImages forState:MJRefreshHeaderStatePulling];
    // 设置正在刷新的动画
    [self.rightCollection.gifHeader setImages:idleImages forState:MJRefreshHeaderStateRefreshing];
   
    
    // 马上进入刷新状态
    [self.rightCollection.header beginRefreshing];
}

#pragma mark - 上拉加载 -------- 未 实现
- (void)categoriesPullUpRefresh
{
    [self.rightCollection addGifFooterWithRefreshingTarget:self refreshingAction:@selector(giftSortDataRequest)];
    
    NSMutableArray *idleImages = [NSMutableArray array];
    for (NSUInteger i = 0; i < 2; i++)
    {
        UIImage *image = [UIImage imageNamed: [NSString stringWithFormat:@"icon_loading_action%ld@2x",i + 1]];
        [idleImages addObject:image];
    }
    self.rightCollection.gifFooter.refreshingImages = idleImages;
}
@end





































